package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;

    @Qualifier("threadPoolTaskExecutor")
    @Autowired
    private Executor executor;

    @Autowired
    private RedissonClient redissonClient;



    /**
     * 查询专辑 详情
     * @param albumId
     * @return
     */
    @Override
    public Map<String, Object> searchAlbumInfoDetail(Long albumId) {
        //获取专辑详细信息前先判断是否存在布隆过滤器,如果存在则先根据布隆过滤器判断专辑是否存在,避免缓存穿透的情况
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        if(bloomFilter.isExists()){
            log.info("存在布隆过滤器,布隆过滤器开始校验专辑id:{}是否存在",albumId);
            boolean isFlag = bloomFilter.contains(albumId);
            //如果缓存中不存在专辑信息
            if(!isFlag){
                throw new GuiguException(404, "布隆过滤器已校验：专辑不存在");
            }
        }

        //多线程情况下应选用ConcurrentHashMap,普通的HashMap并不是线程安全的
        //如果返回结果为自定义vo类,则没有多线程的安全问题
        Map<String, Object> map = new ConcurrentHashMap<>();

        //异步编排
        //查询专辑信息
        CompletableFuture<AlbumInfo> completableFuture = CompletableFuture.supplyAsync(()->{
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfoById(albumId).getData();
            Assert.notNull(albumInfo,"专辑id:{}信息为空", albumId);
            map.put("albumInfo",albumInfo);
            return albumInfo;
        },executor);

        //查询专辑统计信息
        CompletableFuture<Void> albumInfoStatCF = CompletableFuture.runAsync(()->{
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo,"专辑id:{}统计信息为空", albumId);
            map.put("albumStatVo",albumStatVo);
        });

        //查询专辑分类
        CompletableFuture<Void> baseCategoryCF = completableFuture.thenAcceptAsync(albumInfo -> {
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryViewByCategory3Id(albumInfo.getCategory3Id()).getData();
            Assert.notNull(baseCategoryView, "三级分类id:{}的分类信息不存在",albumInfo.getCategory3Id());
            map.put("baseCategoryView",baseCategoryView);
        });

        //查询主播信息
        CompletableFuture<Void> userInfoCF = completableFuture.thenAcceptAsync(albumInfo ->{
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo,"用户id:{}不存在",AuthContextHolder.getUserId());
            map.put("announcer",userInfoVo);
        });

        CompletableFuture.allOf(
                completableFuture,
                albumInfoStatCF,
                baseCategoryCF,
                userInfoCF
        ).orTimeout(10, TimeUnit.SECONDS).join();
        return map;
    }
}
